#include <iostream>
#include <fstream>
#include <string>
#include <map>

using namespace std;

typedef map<string, string, less<string>, allocator<string> > VALUE_PAIR;


VALUE_PAIR config_vp;


string trim(string str)
{
	string s;
    // Trim Both leading and trailing spaces
    size_t startpos = str.find_first_not_of(" \t"); // Find the first character position after excluding leading blank spaces
    size_t endpos = str.find_last_not_of(" \t"); // Find the first character position from reverse af

    // if all spaces or empty return an empty string
    if(( string::npos == startpos ) || ( string::npos == endpos))
    {
        s = "";
    }
    else
        s = str.substr( startpos, endpos-startpos+1 );
	return s;

}

static int is_comment(string line)
{
    // blank lines are comments
    if(line.size() == 0) return 1;

    // lines starting with # are comments
    if(trim(line)[0] == '#') return 1;

    // lines with only whitespace are comments
    for(unsigned int i = 0; i < line.size(); i++)
        if(!isspace(line[i]))
            return 0;
    return 1;
}

static string attribute(string line)
{
    return trim(line.substr(0, line.find_first_of('=')));
}

static string value(string line)
{
    return trim(line.substr(line.find_first_of('=')+1));
}

int read_config_file(string filename)
{
    ifstream the_file(filename.c_str());

    if(!the_file.is_open())
    {
        cerr << "couldn't read config file.\n";
        return -1;
    }

    string name = "", line;

    while (!the_file.eof())
    {
        getline(the_file, line);

        if(is_comment(line)) continue;

        if ((line.find_first_of('=') == string::npos) || (attribute(line) == "") || (value(line) == ""))
        {
            cerr<<"Warning: ignored bad line in pattern file:\n\t"<<line<<endl;
            continue;
        }
		config_vp[attribute(line)] = value(line);

    }
    return 1;
}

extern "C" int
read_config(char *filename)
{
    VALUE_PAIR::iterator theIterator;

	if (read_config_file(filename) == -1) {
		return -1;
	}
    cout << "Read " << config_vp.size() << " value pairs\n";
    /*         theIterator = config_vp.find("ruifeng");
         if(theIterator != config_vp.end() )    // is 0 - 9
             cout << (*theIterator).second << "\n";
         else    // some character other than 0 - 9
             cout << "[err] ";*/
    theIterator = config_vp.begin();
    while (theIterator != config_vp.end())
    {
        cout << (*theIterator).first << "=" << (*theIterator).second << "\n";
        theIterator++;
    }
	return config_vp.size();
}

extern "C" const char *
get_config(char *value)
{
    VALUE_PAIR::iterator theIterator;
    theIterator = config_vp.find(value);
    if(theIterator != config_vp.end())
        return (*theIterator).second.c_str();
    else    // some character other than 0 - 9
        return NULL;
}